'use strict'

let Promise = require('bluebird')
let request = Promise.promisify(require('request'))

let prefix = 'https://api.weixin.qq.com/cgi-bin/token'
let api = {
    accessToken : `${prefix}?grant_type=client_credential`
}

function Wechat(opts){
    let that = this
    this.appId = opts.appId
    this.appsecret = opts.appsecret
    this.getAccessToken = opts.getAccessToken
    this.saveAccessToken = opts.saveAccessToken

    this.getAccessToken().then( data => {
        try{
            data = JSON.parse(data)
        }catch(e){
            return that.updateAccessToken()
        }

        if(that.isValidAccessToken(data)){
            Promise.resolve(data)
        }else{
            return that.updateAccessToken()
        }
    }).then(data=>{
        that.access_token = data.access_token
        that.expires_in = data.expires_in

        that.saveAccessToken(data)
    })
}

Wechat.prototype.isValidAccessToken = function(data){
    if(!data || !data.access_token || !data.expires_in){
        return false
    }

    let access_token= data.access_token
    let expires_in = data.expires_in
    let now = (new Date().getTime())

    if(now < expires_in){
        return true
    }else{
        return false
    }
}

Wechat.prototype.updateAccessToken = function(){
    let appId = this.appId
    let appsecret = this.appsecret
    let url = `${api.accessToken}&appId=${appId}&secret=${appsecret}`

    return new Promise((resolve,reject) => {
        request({
            url: url, json: true
        }).then(response => {
            let data = response.body
            let now = (new Date().getTime())
            let expires_in = now + (data.expires_in - 20) * 1000
    
            data.expires_in = expires_in

            resolve(data)
        })
    })
    
}

module.exports = Wechat